<template>
    <div class="m_right">
        <p></p>
        <div class="mem_tit">商品修改</div>
        <table class="order-wrapper">
            <tr>
                <td>一级分类：</td>
                <td>
                    <select v-model="categoryLevel1Id" @change="cat1Change">
                        <option disabled value="">请选择</option>
                        <option v-for="c in cat1List" :key="c.id" :value="c.id">
                            {{ c.name }}
                        </option>
                    </select>
                    <span v-if="!valid.categoryValid" class="error-tip">请选择一级分类</span>
                </td>
            </tr>
            <tr v-if="hasLevel2">
                <td>二级分类：</td>
                <td>
                    <select v-model="categoryLevel2Id" @change="cat2Change" :disabled="!categoryLevel1Id">
                        <option disabled value="">请选择</option>
                        <option v-for="c in cat2List" :key="c.id" :value="c.id">
                            {{ c.name }}
                        </option>
                    </select>
                    <span v-if="!valid.categoryValid" class="error-tip">请选择二级分类</span>
                </td>
            </tr>
            <tr v-if="hasLevel3">
                <td>三级分类：</td>
                <td>
                    <select v-model="categoryLevel3Id" :disabled="!categoryLevel2Id">
                        <option disabled value="">请选择</option>
                        <option v-for="c in cat3List" :key="c.id" :value="c.id">
                            {{ c.name }}
                        </option>
                    </select>
                    <span v-if="!valid.categoryValid" class="error-tip">请选择三级分类</span>
                </td>
            </tr>
            <tr>
                <td>商品名称：</td>
                <td>
                    <input type="text" name="name" v-model="name" @blur="checkname()" @focus="clearNameError()">(必填)
                    <span v-if="!valid.nameValid" class="error-tip">请填写商品名称</span>
                </td>
            </tr>
            <tr>
                <td>商品图片：</td>
                <td>
                    <img :src="previewImage" width="70px">
                    <input type="file" name="file" @change="handleSelectImg" ref="fileInput">
                </td>
            </tr>
            <tr>
                <td>单价：</td>
                <td>
                    <input type="number" name="price" v-model="price" @blur="checkprice()" @focus="clearPriceError()">
                    <span v-if="!valid.priceValid" class="error-tip">请正确填写商品价格</span>
                </td>
            </tr>
            <tr>
                <td>库存：</td>
                <td>
                    <input type="number" name="stock" v-model="stock" @blur="checkstock()" @focus="clearStockError()">
                    <span v-if="!valid.stockValid" class="error-tip">请正确填写商品库存</span>
                </td>
            </tr>
            <tr>
                <td>描述：</td>
                <td>
                    <textarea name="description" @blur="checkdescription()" @focus="clearDescriptionError()" cols="55"
                        rows="10" v-model="description"></textarea>
                    <span v-if="!valid.descriptionValid" class="error-tip">请填写商品描述</span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="确认修改" @click="submitForm()">&nbsp;&nbsp;
                    <input type="button" value="重置" @click="resetForm()">&nbsp;&nbsp;
                    <input type="button" value="返回" @click="backProList()">
                </td>
            </tr>
        </table>
    </div>
</template>

<script>

export default {
    props: {
        productId: {
            type: Number,
            required: true
        }
    },
    name: 'MemberProductUpdateRight',
    computed: {
        /* 是否有二级 */
        hasLevel2() {
            if (!this.categoryLevel1Id) return false;
            const node = this.treeData.find(n => n.id === this.categoryLevel1Id);
            return !!(node && node.children && node.children.length);
        },
        // 当前二级节点下是否有三级
        hasLevel3() {
            if (!this.categoryLevel2Id) return false;
            const node = this.cat2List.find(n => n.id === this.categoryLevel2Id);
            return !!(node && node.children && node.children.length);
        }
    },
    data() {
        return {
            // 原始商品信息
            snapshot: {
                name: '',
                previewImage: '',
                price: '',
                stock: '',
                description: '',
                categoryLevel1Id: '',
                categoryLevel2Id: '',
                categoryLevel3Id: '',
                /* 如果以后还有别的字段，继续往这里加即可 */
            },

            // 提交商品数据
            name: '',
            previewImage: 'http://192.168.144.183:9090/easybuyImages/null.png',
            price: '',
            stock: '',
            description: '',
            fileName: '',
            file: null,     // 把当前文件存下来，后续上传用
            //校验数据是否合法
            valid: {
                nameValid: true,
                priceValid: true,
                stockValid: true,
                descriptionValid: true,
                fileOK: false,
                categoryValid: true
            },
            // 获取选择框
            /* 以下 3 个是最终提交用的 id */
            categoryLevel1Id: '',
            categoryLevel2Id: '',
            categoryLevel3Id: '',

            /* 下拉选项 */
            cat1List: [],   // 一级
            cat2List: [],   // 二级
            cat3List: [],   // 三级

            // 返回的树形数据
            treeData: [],
        }
    },
    methods: {
        // 获取商品数据
        getProduct() {
            this.$axios({
                url: '/selectProductById',
                method: 'get',
                params: {
                    id: this.productId
                }
            }).then(rs => {
                console.log("商品数据", rs)
                // 数据初始化
                this.snapshot = rs.data.product
                console.log("临时商品数据", this.snapshot)

                // 数据绑定
                this.name = rs.data.product.name;
                this.price = rs.data.product.price;
                this.stock = rs.data.product.stock;
                this.description = rs.data.product.description;
                this.fileName = rs.data.product.fileName;
                //this.categoryLevel1Id = rs.data.product.categoryLevel1Id;
                this.previewImage = rs.data.product.fileName
                    ? `http://192.168.144.183:9090/easybuyImages/${rs.data.product.fileName}`
                    : 'http://192.168.144.183:9090/easybuyImages/null.png';

                console.log('getProduct 完成', this.snapshot)
            })
        },
        /* 1. 首次拉取一级（你的方法稍作改造） */
        getRootCategroies() {
            this.$axios.get('/selectRootCategories').then(rs => {
                if (rs.data.code === 5200) {
                    this.treeData = rs.data.allCategoryWithChild
                    this.cat1List = this.treeData
                }
            })
        },

        /* 2. 选一级 → 出二级 */
        cat1Change() {
            console.log('cat1Change 被触发，当前一级 ID', this.categoryLevel1Id)
            this.categoryLevel2Id = ''
            this.categoryLevel3Id = ''
            this.cat2List = []   // 先清空
            this.cat3List = []
            const node = this.treeData.find(n => n.id === this.categoryLevel1Id)
            console.log('找到的节点', node)
            if (node && node.children) {
                this.cat2List = node.children
                console.log('cat2List 被赋值为', this.cat2List)
            } else {
                console.log('没有找到子级，cat2List 保持空')
            }
        },

        /* 3. 选二级 → 出三级 */
        cat2Change() {
            this.categoryLevel3Id = ''
            this.cat3List = []
            const node = this.cat2List.find(n => n.id === this.categoryLevel2Id)
            if (node && node.children) {
                this.cat3List = node.children
            }
        },
        handleSelectImg(e) {
            const file = e.target.files[0];
            // // 1. 必须上传文件
            // if (!file) {
            //     alert('请上传商品图片');
            //     e.target.value = '';
            //     this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png';
            //     return;
            // }

            // 2. 必须是图片
            if (!file.type.startsWith('image/')) {
                alert('只能上传图片格式（如 jpg、png、gif）');
                e.target.value = '';
                this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png';
                return;
            }

            // 3. 大小 ≤ 2 MB
            const maxSize = 2 * 1024 * 1024; // 2MB 转字节
            if (file.size > maxSize) {
                alert('图片大小不能超过 2MB');
                e.target.value = '';
                this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png';
                return;
            }
            this.file = file
            this.valid.fileOK = true
            // 生成本地临时 URL 并赋值
            this.previewImage = URL.createObjectURL(file)
        },
        // 重置表单
        resetForm() {
            // this.name = this.snapshot.name
            // // 1. 清空文件域
            // this.$refs.fileInput.value = this.snapshot.fileName
            // this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png'
            // this.price = this.snapshot.price
            // this.stock = this.snapshot.stock
            // this.description = this.snapshot.description
            this.getProduct()
        },
        // 校验
        /* 专门校验分类层级 */
        checkCategory() {
            if (!this.categoryLevel1Id) {
                this.valid.categoryValid = false;
                return false;
            }
            if (this.hasLevel2 && !this.categoryLevel2Id) {
                this.valid.categoryValid = false;
                return false;
            }
            if (this.hasLevel3 && !this.categoryLevel3Id) {
                this.valid.categoryValid = false;
                return false;
            }
            this.valid.categoryValid = true;
            return true;
        },
        checkname() {
            this.valid.nameValid = !!this.name.trim()
        },
        checkprice() {
            this.valid.priceValid = this.stock !== ''
            this.valid.priceValid = this.price > 0
        },
        checkstock() {
            const stockNum = Number(this.stock);
            this.valid.stockValid = this.stock !== '' && stockNum > 0 && Number.isInteger(stockNum);
        },
        checkdescription() {
            this.valid.descriptionValid = !!this.description.trim()
        },
        // 获取焦点清除错误信息
        clearNameError() {
            this.valid.nameValid = true
        },
        clearPriceError() {
            this.valid.priceValid = true
        },
        clearStockError() {
            this.valid.stockValid = true
        },
        clearDescriptionError() {
            this.valid.descriptionValid = true
        },
        // 提交表单
        submitForm() {
            // 校验
            this.checkname()
            this.checkprice()
            this.checkstock()
            this.checkdescription()
            this.checkCategory()
            if (!this.valid.nameValid || !this.valid.priceValid || !this.valid.stockValid || !this.valid.descriptionValid || !this.valid.categoryValid) {
                alert('请填写正确商品的信息')
                return
            }
            // 校验通过，提交表单
            // 2. 组装 JSON Blob
            const productJson = {
                id: this.productId,
                name: this.name,
                price: this.price,
                stock: this.stock,
                description: this.description,
                categoryLevel1Id: this.categoryLevel1Id,
                categoryLevel2Id: this.categoryLevel2Id || 0,
                categoryLevel3Id: this.categoryLevel3Id || 0,
                fileName: this.fileName
            };
            const productBlob = new Blob([JSON.stringify(productJson)], { type: 'application/json' });

            // 3. 组装 FormData
            const fd = new FormData();
            fd.append('product', productBlob);
            if (this.snapshot.fileOK === true) {
                fd.append('file', this.file);
            }

            this.$axios({
                url: '/updateProduct',
                method: 'post',
                data: fd,
                header: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(rs => {
                console.log("商品添加", rs)
                if (rs.data.code === 5200) {
                    this.$emit('changeView', 'MemberProductListRight');
                } else {
                    alert("修改商品失败")
                }
            })
        },
        backProList() {
            this.$emit('changeView', 'MemberProductListRight');
        }
    },
    mounted() {
        this.getRootCategroies()
        this.getProduct()
        console.log('getProduct 完成', this.snapshot)
    },
    watch: {
        /* 一级树一旦就位，立即回显一级，并触发后续二级、三级 */
        treeData: {
            handler(val) {
                if (val.length && this.snapshot.categoryLevel1Id) {
                    // 先让 option 渲染出来，再写回 v-model
                    this.$nextTick(() => {
                        this.categoryLevel1Id = this.snapshot.categoryLevel1Id
                        this.$nextTick(() => this.cat1Change()) // 再加载二、三级
                    })
                }
            },
            immediate: true
        },
        cat2List(list) {
            console.log('cat2List 变化', list)
            if (list.length && this.snapshot.categoryLevel2Id) {
                this.categoryLevel2Id = this.snapshot.categoryLevel2Id
                this.$nextTick(() => this.cat2Change())
            }
        },
        cat3List(list) {
            console.log('cat3List 变化', list)
            if (list.length && this.snapshot.categoryLevel3Id) {
                this.categoryLevel3Id = this.snapshot.categoryLevel3Id
            }
        }
    }

}

</script>


<style scoped>
/* —— 订单相关：宽度 85% 并居中 —— */
.order-wrapper {
    width: 85%;
    margin: 20px auto;
    /* 居中 */
    border: 1px solid #dcdfe6;
    /* 新增：外边框 */
    border-radius: 4px;
    /* 可选：圆角更美观 */
    padding: 15px;
    /* 可选：让边框与内容留点空隙 */
    border-collapse: collapse;
    /* 合并边框，避免双线 */
}

.order-wrapper td:first-child {
    width: 30%;
    text-align: right;
    padding-right: 10px;
    /* 可选：让文字和右边的内容有些间距 */
}

/* 统一给所有单元格加边框 */
.order-wrapper td,
.order-wrapper th {
    border: 1px solid #ccc;
    padding: 6px 8px;
    /* 让文字不贴边 */
}

/* 第一个 td：30% 宽 + 文字靠右 */
.order-wrapper td:first-child {
    width: 30%;
    text-align: right;
    padding-right: 10px;
}

/* 错误提示 */
input.error,
textarea.error {
    border: 1px solid #ff4e00;
}

.error-tip {
    color: #ff4e00;
    font-size: 12px;
    margin-left: 6px;
}
</style>